package com.cac.demo.service.deliveryPlan;

import com.cac.demo.controller.CallInterFace.SendMaterialInterface;
import com.cac.demo.dao.deliveryPlan.DeliveryPlanDao;
import com.cac.demo.service.dispatchSearch.MsDeliveryPackageInfoService;
import com.cac.demo.util.adapter.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class DeliveryPlanService {
    @Autowired
    private DeliveryPlanDao deliveryPlanDao;
    @Autowired
    private SendMaterialInterface sendMaterialInterface;
    @Autowired
    private MsDeliveryPackageInfoService msDeliveryPackageInfoService;
    @Autowired
    private Environment environment;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;


    //修改交接单状态(作废改为已移交)
    public Integer updatedeliveryStatus(String wmsDeliveryPlanId){
        Integer data= deliveryPlanDao.updatedeliveryStatus(wmsDeliveryPlanId);
        return  data;
    }
    //修改质量编号
    public void UpdateQualityCode(String wmsDeliveryPlanId, String itemCode){
        deliveryPlanDao.UpdateQualityCode(wmsDeliveryPlanId, itemCode);
    }


    //库存管理--交接单查询
    public QueryRespBean<HashMap> DeliverPlanQuery(QueryReqBean<HashMap> queryReqBean, String orderBy, String Keywords) {
        QueryRespBean<HashMap> queryRespBean =new QueryRespBean<>();
        try {
            PageHelper.startPage(queryReqBean.getPageParameter());
            HashMap searchParams = queryReqBean.getSearchParams();
            Page<HashMap> dataList = deliveryPlanDao.DeliverPlanQuery(searchParams,orderBy,Keywords);
            queryRespBean.setResult(dataList);
            return queryRespBean;
        }catch (Exception e) {
            throw new DaoException(e.getMessage(), e);
        }
    }
    //零件配送页面条件查询
    public PageInfo DeliverQuery(HashMap queryParam, HashMap page) {
        int currentPage = Integer.parseInt(page.get("currentPage").toString());
        int pageSize = Integer.parseInt(page.get("pageSize").toString());
        com.github.pagehelper.PageHelper.startPage(currentPage,pageSize);
        return new PageInfo(deliveryPlanDao.DeliverQuery(queryParam));
    }

    //撤销移交
    public void MESCancelDelivery(List<HashMap> list){
        for (int i = 0; i <list.size() ; i++) {
            HashMap param =list.get(i);
            deliveryPlanDao.updateDeliveryStatus(param);
        }
    }

    /**
     * 撤销配送 v1.0
     * */
    public ResponseMsg cancelDelivery(List<HashMap> list){
        String groupCode = ComUtil.getId();
        if(list.size()==0){
            return new ResponseMsg().setRetCode("201").setMessage("没有需要撤销的数据");
        }
        //1：更改delivery_plan 表group_code以及 备份原来的group_code，已经更改delivery_status数据
        for(HashMap map : list){
            map.put("groupCode",groupCode);
            deliveryPlanDao.updateDeliveryInfo(map);//更新交接单数据
            deliveryPlanDao.updateWorkbinCarInfo(map);//更新小车信息，状态改为03
        }
        //2：打包以及传递MES
        //网闸数据打包接口所需参数，以及发送文件所需func
        HashMap paramMap = new HashMap();
        String isTest = environment.getProperty("pathProperty.isTest");
        //网闸查询场景编码
        if("true".equals(isTest)){
            paramMap.put("dmsCode", "ms_gzbps_cancel_test");
        }else{
            paramMap.put("dmsCode", "ms_gzbps_cancel");
        }
        //网闸查询数据SQL所需条件
        paramMap.put("delivery_plan_code", groupCode);
        HashMap interfaceMap = new HashMap();
        interfaceMap.put("code", "getMatchData");
        interfaceMap.put("name", "获取数据配套场景的配套数据");
        interfaceMap.put("parameters", paramMap);
        //发送文件所需func
        interfaceMap.put("func", "101-MES-FenjianCancelCancel");
        interfaceMap.put("sendScenario", "物料配送撤销");
        //文件上传ERP
        sendMaterialInterface.SendFileInterface(interfaceMap);
        return new ResponseMsg().setRetCode("200").setMessage("操作成功");
    }

    /**
     * 撤销配送 v2.0 -11-22分拣人员用
     * */
    public ResponseMsg cancelUnDelivery(List<HashMap> list){
        String groupCode = ComUtil.getId();
        if(list.size()==0){
            return new ResponseMsg().setRetCode("201").setMessage("没有需要撤销的数据");
        }
        for(HashMap map : list){
            String status =deliveryPlanDao.searchDeliveryStatus(map);
            if(!status.equals("1")){
                return new ResponseMsg().setRetCode("201").setMessage("包含状态不为未确认的数据，请先撤销移交！");
            }
        }
        for(HashMap map : list){
            map.put("groupCode",groupCode);
            deliveryPlanDao.updateDeliveryInfo(map);//更新交接单数据
            deliveryPlanDao.updateWorkbinCarInfo(map);//更新小车信息，状态改为03
        }
        //2：打包以及传递MES
        HashMap paramMap = new HashMap();
        String isTest = environment.getProperty("pathProperty.isTest");
        //网闸查询场景编码
        if("true".equals(isTest)){
            paramMap.put("dmsCode", "ms_gzbps_cancel_test");
        }else{
            paramMap.put("dmsCode", "ms_gzbps_cancel");
        }
        //网闸查询数据SQL所需条件
        paramMap.put("delivery_plan_code", groupCode);
        HashMap interfaceMap = new HashMap();
        interfaceMap.put("code", "getMatchData");
        interfaceMap.put("name", "获取数据配套场景的配套数据");
        interfaceMap.put("parameters", paramMap);
        //发送文件所需func
        interfaceMap.put("func", "101-MES-CancelUnDelivery");
        interfaceMap.put("sendScenario", "物料配送撤销");
        //文件上传ERP
        sendMaterialInterface.SendFileInterface(interfaceMap);
        return new ResponseMsg().setRetCode("200").setMessage("操作成功");
    }

    /**
     * 重新配送
     * */
    public ResponseMsg reSend(List<HashMap> list){
        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
        ResponseMsg responseMsg = new ResponseMsg();
        String groupCode = ComUtil.getId();
        String carCode = "L-D-00000016";
        try{
            for(HashMap map : list){
                map.put("groupCode",groupCode);
                map.put("carCode",carCode);
                //更新交接单表 group_code
                deliveryPlanDao.updateWmsDeliveryGroupCode(map);
                //更新小车表 group_code以及car_code
                deliveryPlanDao.updateWorkbinCarInfoGroupCode(map);
            }
            //判断当前装车的小车的工作包是是否存在没下日计划的
            if(msDeliveryPackageInfoService.queryPackageExistsDaliyPlan(carCode)){
                String aoCodes = msDeliveryPackageInfoService.queryAoExistsDaliy(carCode);
                responseMsg.setRetCode("201").setMessage("当前已装车的AO存在未下日计划的AO！未下日计划AO如下："+aoCodes);
                platformTransactionManager.rollback(transaction);
                return responseMsg;
            }
            //校验配送小车的物料是否重复
            if(msDeliveryPackageInfoService.existsRepeatDelivery(groupCode)){
                platformTransactionManager.rollback(transaction);
                return responseMsg.setRetCode("201").setMessage("当前配送的物料生成的交接单存在重复数据，请查看ms_delivery_repeat_check表");
            }
            //校验配送过去的物料数量是否超过需求数量
            HashMap re = msDeliveryPackageInfoService.checkSendQty(groupCode);
            if("201".equals(re.get("retCode"))){
                platformTransactionManager.rollback(transaction);
                return responseMsg.setRetCode("201").setMessage((String)re.get("retMsg"));
            }
            //更新当前小车配送状态
            int cnt = msDeliveryPackageInfoService.updateWorkbinCar(carCode);
            platformTransactionManager.commit(transaction);
        }catch (Exception e){
            platformTransactionManager.rollback(transaction);
            e.printStackTrace();
            return responseMsg.setRetCode("201").setMessage("处理业务数据异常");
        }
        HashMap paramMap = new HashMap();
        String isTest = environment.getProperty("pathProperty.isTest");
        //网闸查询场景编码
        if("true".equals(isTest)){
            paramMap.put("dmsCode", "ms_gzbps_test");
        }else{
            paramMap.put("dmsCode", "ms_gzbps");
        }
        //网闸查询数据SQL所需条件
        paramMap.put("delivery_plan_code", groupCode);
        HashMap interfaceMap = new HashMap();
        interfaceMap.put("code", "getMatchData");
        interfaceMap.put("name", "获取数据配套场景的配套数据");
        interfaceMap.put("parameters", paramMap);
        //发送文件所需func
        interfaceMap.put("func", environment.getProperty("dispatch.func"));
        interfaceMap.put("sendScenario", "物料配送");
        //文件上传ERP
        HashMap rsl = sendMaterialInterface.SendFileInterface(interfaceMap);
        if (rsl.get("retCode").equals("200")) {
            responseMsg.setRetCode("200").setMessage("配送数据保存成功！");
        } else {
            responseMsg.setRetCode("201").setMessage("物料数据上传MES失败！");
        }
        return responseMsg;
    }

    /**
     * 重新推送备注
     * */
    public ResponseMsg reSendRemark(List<HashMap> list){
        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
        ResponseMsg responseMsg = new ResponseMsg();
        String groupCode = ComUtil.getId();
        try{
            String carCode = "L-D-00000016";
            for(HashMap map : list){
                map.put("groupCode",groupCode);
                map.put("carCode",carCode);
                //更新交接单表 group_code
                deliveryPlanDao.updateWmsDeliveryGroupCode(map);
                //更新小车表 group_code以及car_code
                deliveryPlanDao.updateWorkbinCarInfoGroupCode(map);
            }
            int cnt = msDeliveryPackageInfoService.updateWorkbinCar(carCode);
            platformTransactionManager.commit(transaction);
        }catch (Exception e){
            platformTransactionManager.rollback(transaction);
            e.printStackTrace();
            return responseMsg.setRetCode("201").setMessage("处理业务数据异常");
        }

        HashMap paramMap = new HashMap();
        String isTest = environment.getProperty("pathProperty.isTest");
        //网闸查询场景编码
        if("true".equals(isTest)){
            paramMap.put("dmsCode", "ms_gzbps_remark_test");
        }else{
            paramMap.put("dmsCode", "ms_gzbps_remark");
        }
        //网闸查询数据SQL所需条件
        paramMap.put("delivery_plan_code", groupCode);
        HashMap interfaceMap = new HashMap();
        interfaceMap.put("code", "getMatchData");
        interfaceMap.put("name", "获取数据配套场景的配套数据");
        interfaceMap.put("parameters", paramMap);
        //发送文件所需func
        interfaceMap.put("func", environment.getProperty("dispatch.func"));
        interfaceMap.put("sendScenario", "物料配送");
        //文件上传ERP
        HashMap rsl = sendMaterialInterface.SendFileInterface(interfaceMap);
        if (rsl.get("retCode").equals("200")) {
            responseMsg.setRetCode("200").setMessage("配送数据保存成功！");
        } else {
            responseMsg.setRetCode("201").setMessage("物料数据上传MES失败！");
        }
        return responseMsg;
    }

    public ResponseMsg updateRemark(HashMap map){
        ResponseMsg responseMsg = new ResponseMsg();
        int count =deliveryPlanDao.updateWmsDeliveryRemark(map);
        if(count ==0){
            responseMsg.setRetCode("201").setMessage("修改失败");
        }else {
            responseMsg.setRetCode("200").setMessage("修改成功");
        }
        return responseMsg;
    }

    public ResponseMsg updateWmsDelivery(HashMap map){
        ResponseMsg responseMsg = new ResponseMsg();
        int count =deliveryPlanDao.updateWmsDelivery(map);
        if(count ==0){
            responseMsg.setRetCode("201").setMessage("修改失败");
        }else {
            responseMsg.setRetCode("200").setMessage("修改成功");
        }
        return responseMsg;
    }

    public ResponseMsg updateWmsDeliveryStatus(HashMap map){
        ResponseMsg responseMsg = new ResponseMsg();
        int count =deliveryPlanDao.updateWmsDeliveryStatus(map);
        if(count ==0){
            responseMsg.setRetCode("201").setMessage("修改失败");
        }else {
            responseMsg.setRetCode("200").setMessage("修改成功");
        }
        return responseMsg;
    }
}
